package dto;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

import model.Comment;

public class DtoComment {
	public static List<Comment> getAll(DataManager dataManager, String sql) {
		List<Comment> comments = new ArrayList<Comment>();
		
		Connection conn = dataManager.getConnection();
		Statement statement = null;
		ResultSet rs = null;
		if (conn != null) {
			try {
				statement = conn.createStatement();
				
				rs = statement.executeQuery(sql);
				comments = new ArrayList<Comment>();
				while (rs.next()) {
					Comment comment = new Comment();
					comment.setCommentId(rs.getInt("commentId"));
					comment.setUserId(rs.getInt("userId"));
					comment.setProductId(rs.getInt("productId"));
					comment.setUsercomment(rs.getString("usercomment"));
					
					comments.add(comment);
				}
			} catch (SQLException e) {
				e.printStackTrace();
			} finally {
				try {
					if (rs != null) 
						rs.close();
					if(statement != null)
						statement.close();
					conn.close();
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
		return comments;
	}
	
	public static List<Comment> getAllByProductId(DataManager dataManager, int productId)
	{
		String sql = "select * from Comment where productId = " + productId;
		return getAll(dataManager, sql);
	}
	
	public static boolean insert(Comment commnent, DataManager dataManager)
	{
		Connection conn = dataManager.getConnection();
		Statement st = null;
		boolean check = false;
		String sql = "insert into Comment(userId,productId,usercomment) " +
				"values ("+commnent.getUserId()+","+commnent.getProductId()+",'"+commnent.getUsercomment()+"')";
		if(conn!= null)
		{
			try {
				st = conn.createStatement();
				
				int rs = st.executeUpdate(sql);
				if(rs > 0) 
					check = true;
			} catch (SQLException e) {
				System.out.println("loi cau sql : " + sql);
			}
			finally
			{
				try {
					
					if(st != null)
						st.close();
					conn.close();
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
		
		return check;
		
	}
	
	
	
}
